#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Linux权限维持一键化测试脚本
专门测试HackerPermKeeper T00ls的权限维持功能
"""

import os
import sys
import json
import time
import subprocess
import argparse
import logging
from datetime import datetime
from pathlib import Path

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    input = raw_input

class LinuxPersistenceTester:
    """Linux权限维持一键化测试器"""
    
    def __init__(self, target_ip=None, target_user="root"):
        self.target_ip = target_ip
        self.target_user = target_user
        self.test_session_id = datetime.now().strftime('%Y%m%d_%H%M%S')
        self.test_results = {}
        self.deployed_backdoors = []
        
        # 设置日志
        self.setup_logging()
        
        # 测试配置
        self.test_config = {
            'ssh_port': 22,
            'reverse_shell_port': 4444,
            'test_timeout': 300,  # 5分钟超时
            'cleanup_enabled': True
        }
        
        # 权限维持类型
        self.persistence_types = [
            'ssh_key',
            'systemd_service', 
            'crontab',
            'env_variable',
            'file_trigger',
            'bashrc_alias'
        ]
    
    def setup_logging(self):
        """设置日志记录"""
        log_dir = "logs"
        os.makedirs(log_dir, exist_ok=True)
        
        log_file = f"{log_dir}/persistence_test_{self.test_session_id}.log"
        
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(log_file),
                logging.StreamHandler(sys.stdout)
            ]
        )
        
        self.logger = logging.getLogger(__name__)
        self.logger.info(f"Linux权限维持测试开始 - 会话ID: {self.test_session_id}")
    
    def check_prerequisites(self):
        """检查测试前提条件"""
        self.logger.info("检查测试前提条件...")
        
        # 检查核心必需工具
        core_required_tools = ['ssh', 'systemctl', 'crontab']
        missing_core_tools = []
        
        for tool in core_required_tools:
            if not self._command_exists(tool):
                missing_core_tools.append(tool)
        
        if missing_core_tools:
            self.logger.error(f"缺少核心必需工具: {', '.join(missing_core_tools)}")
            self.logger.error("请安装缺少的工具后重试")
            return False
        
        # 检查可选工具
        optional_tools = ['scp', 'nc', 'nmap', 'netstat', 'ps']
        missing_optional_tools = []
        
        for tool in optional_tools:
            if not self._command_exists(tool):
                missing_optional_tools.append(tool)
        
        if missing_optional_tools:
            self.logger.warning(f"缺少可选工具: {', '.join(missing_optional_tools)}")
            self.logger.warning("某些高级功能可能无法使用，但基本测试可以继续")
        
        # 检查目标连通性
        if self.target_ip:
            if not self._check_target_connectivity():
                self.logger.error(f"无法连接到目标主机: {self.target_ip}")
                return False
        
        self.logger.info("前提条件检查通过")
        return True
    
    def _command_exists(self, command):
        """检查命令是否存在"""
        try:
            subprocess.run(['which', command], 
                         capture_output=True, check=True)
            return True
        except subprocess.CalledProcessError:
            return False
    
    def _check_target_connectivity(self):
        """检查目标主机连通性"""
        try:
            result = subprocess.run(
                ['ping', '-c', '3', self.target_ip],
                capture_output=True, timeout=10
            )
            return result.returncode == 0
        except subprocess.TimeoutExpired:
            return False
    
    def test_local_persistence_deployment(self):
        """测试本地权限维持部署"""
        self.logger.info("开始测试本地权限维持部署...")
        
        test_results = {}
        
        # 导入权限维持模块
        try:
            sys.path.append('../modules/automation')
            from one_click_integration import OneClickIntegration
            
            # 创建一键化集成实例
            integration = OneClickIntegration()
            
            # 测试环境分析
            self.logger.info("执行环境分析...")
            if integration.analyze_environment():
                test_results['environment_analysis'] = True
                self.logger.info("✓ 环境分析成功")
            else:
                test_results['environment_analysis'] = False
                self.logger.error("✗ 环境分析失败")
                return test_results
            
            # 测试策略生成
            self.logger.info("生成部署策略...")
            if integration.generate_strategy():
                test_results['strategy_generation'] = True
                self.logger.info("✓ 策略生成成功")
            else:
                test_results['strategy_generation'] = False
                self.logger.error("✗ 策略生成失败")
                return test_results
            
            # 测试一键化部署
            self.logger.info("执行一键化部署...")
            if integration.one_click_deploy():
                test_results['one_click_deployment'] = True
                self.logger.info("✓ 一键化部署成功")
                
                # 记录部署的后门
                if hasattr(integration, 'deployment_records'):
                    self.deployed_backdoors = integration.deployment_records
                    
            else:
                test_results['one_click_deployment'] = False
                self.logger.error("✗ 一键化部署失败")
                return test_results
            
            # 测试后门验证
            self.logger.info("验证后门状态...")
            if integration.verify_backdoors():
                test_results['backdoor_verification'] = True
                self.logger.info("✓ 后门验证成功")
            else:
                test_results['backdoor_verification'] = False
                self.logger.error("✗ 后门验证失败")
            
        except ImportError as e:
            self.logger.error(f"无法导入权限维持模块: {e}")
            test_results['module_import'] = False
            return test_results
        except Exception as e:
            self.logger.error(f"权限维持部署测试异常: {e}")
            test_results['deployment_exception'] = str(e)
            return test_results
        
        return test_results
    
    def test_persistence_types(self):
        """测试各种权限维持类型"""
        self.logger.info("测试各种权限维持类型...")
        
        type_results = {}
        
        for persistence_type in self.persistence_types:
            self.logger.info(f"测试 {persistence_type} 权限维持...")
            
            try:
                result = self._test_single_persistence_type(persistence_type)
                type_results[persistence_type] = result
                
                if result['deployed']:
                    self.logger.info(f"✓ {persistence_type} 部署成功")
                else:
                    self.logger.warning(f"✗ {persistence_type} 部署失败")
                    
            except Exception as e:
                self.logger.error(f"{persistence_type} 测试异常: {e}")
                type_results[persistence_type] = {
                    'deployed': False,
                    'error': str(e)
                }
        
        return type_results
    
    def _test_single_persistence_type(self, persistence_type):
        """测试单个权限维持类型"""
        result = {
            'deployed': False,
            'persistent': False,
            'stealth': False,
            'accessible': False
        }
        
        if persistence_type == 'ssh_key':
            result = self._test_ssh_key_backdoor()
        elif persistence_type == 'systemd_service':
            result = self._test_systemd_service_backdoor()
        elif persistence_type == 'crontab':
            result = self._test_crontab_backdoor()
        elif persistence_type == 'env_variable':
            result = self._test_env_variable_backdoor()
        elif persistence_type == 'file_trigger':
            result = self._test_file_trigger_backdoor()
        elif persistence_type == 'bashrc_alias':
            result = self._test_bashrc_alias_backdoor()
        
        return result
    
    def _test_ssh_key_backdoor(self):
        """测试SSH密钥后门"""
        result = {'deployed': False, 'persistent': False, 'stealth': False, 'accessible': False}
        
        try:
            # 检查SSH密钥文件
            key_paths = [
                os.path.expanduser('~/.ssh/.hidden_key'),
                os.path.expanduser('~/.ssh/.system_key'),
                os.path.expanduser('~/.ssh/.backup_key')
            ]
            
            for key_path in key_paths:
                if os.path.exists(key_path):
                    result['deployed'] = True
                    self.logger.info(f"发现SSH密钥: {key_path}")
                    
                    # 检查密钥权限
                    stat_info = os.stat(key_path)
                    if oct(stat_info.st_mode)[-3:] == '600':
                        result['stealth'] = True
                    
                    break
            
            # 检查authorized_keys
            auth_keys_path = os.path.expanduser('~/.ssh/authorized_keys')
            if os.path.exists(auth_keys_path):
                with open(auth_keys_path, 'r') as f:
                    content = f.read()
                    if 'system-backup-key' in content or 'hidden' in content:
                        result['persistent'] = True
            
            # 测试SSH连接（如果有目标IP）
            if self.target_ip and result['deployed']:
                result['accessible'] = self._test_ssh_connection()
                
        except Exception as e:
            self.logger.error(f"SSH密钥后门测试异常: {e}")
        
        return result
    
    def _test_systemd_service_backdoor(self):
        """测试Systemd服务后门"""
        result = {'deployed': False, 'persistent': False, 'stealth': False, 'accessible': False}
        
        try:
            # 检查可疑服务
            suspicious_services = [
                'log-cleaner.service',
                'system-maintenance.service',
                'backup-service.service'
            ]
            
            for service in suspicious_services:
                service_path = f'/etc/systemd/system/{service}'
                if os.path.exists(service_path):
                    result['deployed'] = True
                    self.logger.info(f"发现Systemd服务: {service}")
                    
                    # 检查服务状态
                    try:
                        status_result = subprocess.run(
                            ['systemctl', 'is-enabled', service],
                            capture_output=True, text=True
                        )
                        if status_result.returncode == 0:
                            result['persistent'] = True
                    except:
                        pass
                    
                    # 检查服务隐蔽性（描述和名称）
                    with open(service_path, 'r') as f:
                        content = f.read()
                        if 'system' in content.lower() or 'maintenance' in content.lower():
                            result['stealth'] = True
                    
                    break
            
            # 测试服务触发
            if result['deployed']:
                result['accessible'] = self._test_service_trigger()
                
        except Exception as e:
            self.logger.error(f"Systemd服务后门测试异常: {e}")
        
        return result
    
    def _test_crontab_backdoor(self):
        """测试Crontab后门"""
        result = {'deployed': False, 'persistent': False, 'stealth': False, 'accessible': False}
        
        try:
            # 检查用户crontab
            crontab_result = subprocess.run(
                ['crontab', '-l'], 
                capture_output=True, text=True
            )
            
            if crontab_result.returncode == 0:
                crontab_content = crontab_result.stdout
                
                # 查找可疑的cron任务
                suspicious_patterns = [
                    'system-check',
                    'maintenance',
                    '/tmp/',
                    'bash -c'
                ]
                
                for pattern in suspicious_patterns:
                    if pattern in crontab_content:
                        result['deployed'] = True
                        result['persistent'] = True
                        self.logger.info(f"发现可疑cron任务: {pattern}")
                        
                        # 检查隐蔽性（注释和时间）
                        if '#' in crontab_content and 'System' in crontab_content:
                            result['stealth'] = True
                        
                        break
            
            # 检查系统cron目录
            system_cron_dirs = ['/etc/cron.d/', '/etc/cron.hourly/', '/etc/cron.daily/']
            for cron_dir in system_cron_dirs:
                if os.path.exists(cron_dir):
                    for file in os.listdir(cron_dir):
                        if file.startswith('.') or 'system' in file:
                            result['deployed'] = True
                            break
            
            # 测试cron触发
            if result['deployed']:
                result['accessible'] = self._test_cron_trigger()
                
        except Exception as e:
            self.logger.error(f"Crontab后门测试异常: {e}")
        
        return result
    
    def _test_env_variable_backdoor(self):
        """测试环境变量后门"""
        result = {'deployed': False, 'persistent': False, 'stealth': False, 'accessible': False}
        
        try:
            # 检查profile.d目录
            profile_d_path = '/etc/profile.d/'
            if os.path.exists(profile_d_path):
                for file in os.listdir(profile_d_path):
                    if file.startswith('.') and file.endswith('.sh'):
                        file_path = os.path.join(profile_d_path, file)
                        
                        with open(file_path, 'r') as f:
                            content = f.read()
                            
                        # 查找可疑的环境变量
                        if 'SYSTEM_PATH_CACHE' in content or 'maintenance_mode' in content:
                            result['deployed'] = True
                            result['persistent'] = True
                            result['stealth'] = True  # 隐藏文件名
                            self.logger.info(f"发现环境变量后门: {file}")
                            break
            
            # 检查当前环境变量
            env_vars = os.environ
            suspicious_vars = ['SYSTEM_PATH_CACHE', 'MAINTENANCE_MODE', 'BACKUP_PATH']
            
            for var in suspicious_vars:
                if var in env_vars:
                    result['accessible'] = True
                    break
                    
        except Exception as e:
            self.logger.error(f"环境变量后门测试异常: {e}")
        
        return result
    
    def _test_file_trigger_backdoor(self):
        """测试文件触发后门"""
        result = {'deployed': False, 'persistent': False, 'stealth': False, 'accessible': False}
        
        try:
            # 检查触发文件
            trigger_files = ['/tmp/.sync', '/var/log/.sync.log', '/tmp/.trigger']
            monitor_scripts = ['/usr/local/bin/file-monitor', '/usr/bin/system-monitor']
            
            for trigger_file in trigger_files:
                if os.path.exists(trigger_file):
                    result['deployed'] = True
                    result['stealth'] = True  # 隐藏文件
                    self.logger.info(f"发现触发文件: {trigger_file}")
                    break
            
            for monitor_script in monitor_scripts:
                if os.path.exists(monitor_script):
                    result['persistent'] = True
                    self.logger.info(f"发现监控脚本: {monitor_script}")
                    break
            
            # 测试文件触发
            if result['deployed']:
                result['accessible'] = self._test_file_trigger()
                
        except Exception as e:
            self.logger.error(f"文件触发后门测试异常: {e}")
        
        return result
    
    def _test_bashrc_alias_backdoor(self):
        """测试Bashrc别名后门"""
        result = {'deployed': False, 'persistent': False, 'stealth': False, 'accessible': False}
        
        try:
            # 检查shell配置文件
            shell_configs = [
                os.path.expanduser('~/.bashrc'),
                os.path.expanduser('~/.zshrc'),
                '/etc/bash.bashrc'
            ]
            
            for config_file in shell_configs:
                if os.path.exists(config_file):
                    with open(config_file, 'r') as f:
                        content = f.read()
                    
                    # 查找可疑别名
                    suspicious_aliases = ['alias ls=', 'alias ps=', 'alias netstat=']
                    
                    for alias in suspicious_aliases:
                        if alias in content:
                            result['deployed'] = True
                            result['persistent'] = True
                            result['stealth'] = True
                            self.logger.info(f"发现别名后门: {alias}")
                            break
            
            # 测试别名功能
            if result['deployed']:
                result['accessible'] = self._test_alias_function()
                
        except Exception as e:
            self.logger.error(f"Bashrc别名后门测试异常: {e}")
        
        return result
    
    def _test_ssh_connection(self):
        """测试SSH连接"""
        try:
            # 这里应该使用部署的SSH密钥进行连接测试
            # 由于安全考虑，这里只做模拟测试
            self.logger.info("模拟SSH连接测试...")
            return True
        except:
            return False
    
    def _test_service_trigger(self):
        """测试服务触发"""
        try:
            # 创建触发文件测试服务响应
            trigger_file = '/tmp/.service_trigger'
            with open(trigger_file, 'w') as f:
                f.write('test')
            
            time.sleep(2)
            
            # 检查响应文件
            response_file = '/tmp/.service_response'
            if os.path.exists(response_file):
                os.remove(response_file)
                os.remove(trigger_file)
                return True
            
            os.remove(trigger_file)
            return False
        except:
            return False
    
    def _test_cron_trigger(self):
        """测试Cron触发"""
        try:
            # 创建cron触发文件
            trigger_file = '/tmp/.cron_trigger'
            cmd_file = '/tmp/.cron_cmd'
            
            with open(trigger_file, 'w') as f:
                f.write('test')
            
            with open(cmd_file, 'w') as f:
                f.write('echo "cron_test" > /tmp/.cron_output')
            
            time.sleep(5)
            
            # 检查输出文件
            output_file = '/tmp/.cron_output'
            if os.path.exists(output_file):
                os.remove(output_file)
                return True
            
            return False
        except:
            return False
    
    def _test_file_trigger(self):
        """测试文件触发"""
        try:
            # 创建触发文件
            trigger_file = '/tmp/.sync'
            with open(trigger_file, 'w') as f:
                f.write('trigger_test')
            
            time.sleep(3)
            
            # 检查响应
            response_file = '/var/log/.sync.log'
            if os.path.exists(response_file):
                return True
            
            return False
        except:
            return False
    
    def _test_alias_function(self):
        """测试别名功能"""
        try:
            # 测试别名是否生效
            result = subprocess.run(
                ['bash', '-c', 'alias ls'],
                capture_output=True, text=True
            )
            
            if 'ls=' in result.stdout:
                return True
            
            return False
        except:
            return False
    
    def test_stealth_capabilities(self):
        """测试隐蔽性能力"""
        self.logger.info("测试隐蔽性能力...")
        
        stealth_results = {}
        
        # 测试文件隐藏
        stealth_results['file_hiding'] = self._test_file_hiding()
        
        # 测试进程隐藏
        stealth_results['process_hiding'] = self._test_process_hiding()
        
        # 测试日志清理
        stealth_results['log_cleaning'] = self._test_log_cleaning()
        
        # 测试检测规避
        stealth_results['detection_evasion'] = self._test_detection_evasion()
        
        return stealth_results
    
    def _test_file_hiding(self):
        """测试文件隐藏"""
        hidden_files_found = 0
        total_files = 0
        
        # 检查隐藏文件
        hidden_paths = [
            '~/.ssh/.hidden_key',
            '/etc/profile.d/.system-env.sh',
            '/tmp/.sync',
            '/var/log/.sync.log'
        ]
        
        for path in hidden_paths:
            expanded_path = os.path.expanduser(path)
            total_files += 1
            
            if os.path.exists(expanded_path):
                hidden_files_found += 1
                
                # 检查文件是否以点开头（隐藏）
                filename = os.path.basename(expanded_path)
                if filename.startswith('.'):
                    self.logger.info(f"发现隐藏文件: {expanded_path}")
        
        return {
            'hidden_files_found': hidden_files_found,
            'total_files': total_files,
            'hiding_rate': hidden_files_found / total_files if total_files > 0 else 0
        }
    
    def _test_process_hiding(self):
        """测试进程隐藏"""
        try:
            # 检查可疑进程
            result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
            processes = result.stdout
            
            suspicious_processes = [
                'file-monitor',
                'system-monitor',
                'log-cleaner',
                'backup-service'
            ]
            
            found_processes = []
            for process in suspicious_processes:
                if process in processes:
                    found_processes.append(process)
            
            return {
                'suspicious_processes': found_processes,
                'process_count': len(found_processes)
            }
            
        except Exception as e:
            self.logger.error(f"进程隐藏测试异常: {e}")
            return {'error': str(e)}
    
    def _test_log_cleaning(self):
        """测试日志清理"""
        try:
            # 检查系统日志中的异常条目
            log_files = [
                '/var/log/auth.log',
                '/var/log/syslog',
                '/var/log/messages'
            ]
            
            suspicious_entries = 0
            
            for log_file in log_files:
                if os.path.exists(log_file):
                    try:
                        with open(log_file, 'r') as f:
                            content = f.read()
                            
                        # 查找可疑条目
                        if 'backdoor' in content.lower() or 'malicious' in content.lower():
                            suspicious_entries += 1
                            
                    except PermissionError:
                        continue
            
            return {
                'suspicious_log_entries': suspicious_entries,
                'logs_checked': len(log_files)
            }
            
        except Exception as e:
            self.logger.error(f"日志清理测试异常: {e}")
            return {'error': str(e)}
    
    def _test_detection_evasion(self):
        """测试检测规避"""
        try:
            evasion_results = {}
            
            # 测试chkrootkit检测
            if self._command_exists('chkrootkit'):
                result = subprocess.run(['chkrootkit'], capture_output=True, text=True)
                evasion_results['chkrootkit'] = 'INFECTED' not in result.stdout
            
            # 测试rkhunter检测
            if self._command_exists('rkhunter'):
                result = subprocess.run(['rkhunter', '--check', '--sk'], 
                                      capture_output=True, text=True)
                evasion_results['rkhunter'] = 'Warning' not in result.stdout
            
            # 测试netstat异常
            result = subprocess.run(['netstat', '-tulpn'], capture_output=True, text=True)
            suspicious_ports = ['4444', '1337', '31337']
            port_detected = any(port in result.stdout for port in suspicious_ports)
            evasion_results['netstat'] = not port_detected
            
            return evasion_results
            
        except Exception as e:
            self.logger.error(f"检测规避测试异常: {e}")
            return {'error': str(e)}
    
    def test_persistence_after_reboot(self):
        """测试重启后持久化"""
        self.logger.info("测试重启后持久化（模拟）...")
        
        # 由于无法真正重启，这里模拟重启后的检查
        persistence_results = {}
        
        # 检查开机自启项
        persistence_results['systemd_services'] = self._check_systemd_persistence()
        persistence_results['cron_jobs'] = self._check_cron_persistence()
        persistence_results['profile_scripts'] = self._check_profile_persistence()
        persistence_results['ssh_keys'] = self._check_ssh_key_persistence()
        
        return persistence_results
    
    def _check_systemd_persistence(self):
        """检查Systemd持久化"""
        try:
            result = subprocess.run(['systemctl', 'list-unit-files', '--state=enabled'],
                                  capture_output=True, text=True)
            
            suspicious_services = ['log-cleaner', 'system-maintenance', 'backup-service']
            enabled_backdoors = []
            
            for service in suspicious_services:
                if service in result.stdout:
                    enabled_backdoors.append(service)
            
            return {
                'enabled_backdoor_services': enabled_backdoors,
                'persistence_count': len(enabled_backdoors)
            }
            
        except Exception as e:
            return {'error': str(e)}
    
    def _check_cron_persistence(self):
        """检查Cron持久化"""
        try:
            result = subprocess.run(['crontab', '-l'], capture_output=True, text=True)
            
            if result.returncode == 0:
                cron_content = result.stdout
                backdoor_jobs = cron_content.count('system-check') + cron_content.count('maintenance')
                
                return {
                    'backdoor_cron_jobs': backdoor_jobs,
                    'total_cron_lines': len(cron_content.split('\n'))
                }
            
            return {'backdoor_cron_jobs': 0}
            
        except Exception as e:
            return {'error': str(e)}
    
    def _check_profile_persistence(self):
        """检查Profile持久化"""
        try:
            profile_d_path = '/etc/profile.d/'
            backdoor_scripts = 0
            
            if os.path.exists(profile_d_path):
                for file in os.listdir(profile_d_path):
                    if file.startswith('.') and file.endswith('.sh'):
                        backdoor_scripts += 1
            
            return {
                'backdoor_profile_scripts': backdoor_scripts
            }
            
        except Exception as e:
            return {'error': str(e)}
    
    def _check_ssh_key_persistence(self):
        """检查SSH密钥持久化"""
        try:
            auth_keys_path = os.path.expanduser('~/.ssh/authorized_keys')
            backdoor_keys = 0
            
            if os.path.exists(auth_keys_path):
                with open(auth_keys_path, 'r') as f:
                    content = f.read()
                
                # 查找后门密钥标识
                backdoor_identifiers = ['system-backup-key', 'hidden', 'maintenance']
                for identifier in backdoor_identifiers:
                    backdoor_keys += content.count(identifier)
            
            return {
                'backdoor_ssh_keys': backdoor_keys
            }
            
        except Exception as e:
            return {'error': str(e)}
    
    def cleanup_test_environment(self):
        """清理测试环境"""
        if not self.test_config['cleanup_enabled']:
            self.logger.info("清理功能已禁用，跳过清理")
            return
        
        self.logger.info("开始清理测试环境...")
        
        try:
            # 导入清理模块
            sys.path.append('../modules/automation')
            from emergency_cleanup import EmergencyCleanup
            
            cleanup = EmergencyCleanup()
            
            # 执行应急清理
            if cleanup.emergency_cleanup():
                self.logger.info("✓ 测试环境清理完成")
                return True
            else:
                self.logger.error("✗ 测试环境清理失败")
                return False
                
        except ImportError:
            self.logger.warning("无法导入清理模块，执行手动清理...")
            return self._manual_cleanup()
        except Exception as e:
            self.logger.error(f"清理过程异常: {e}")
            return False
    
    def _manual_cleanup(self):
        """手动清理"""
        try:
            cleanup_items = [
                # SSH密钥
                os.path.expanduser('~/.ssh/.hidden_key'),
                os.path.expanduser('~/.ssh/.hidden_key.pub'),
                
                # 环境变量脚本
                '/etc/profile.d/.system-env.sh',
                
                # 触发文件
                '/tmp/.sync',
                '/var/log/.sync.log',
                '/tmp/.cron_trigger',
                '/tmp/.cron_cmd',
                '/tmp/.cron_output',
                
                # 监控脚本
                '/usr/local/bin/file-monitor',
                '/usr/bin/system-monitor',
                '/usr/bin/system-check'
            ]
            
            for item in cleanup_items:
                if os.path.exists(item):
                    os.remove(item)
                    self.logger.info(f"已删除: {item}")
            
            # 清理crontab
            try:
                result = subprocess.run(['crontab', '-l'], capture_output=True, text=True)
                if result.returncode == 0:
                    lines = result.stdout.split('\n')
                    clean_lines = [line for line in lines 
                                 if not any(keyword in line for keyword in 
                                          ['system-check', 'maintenance', '/tmp/'])]
                    
                    if len(clean_lines) != len(lines):
                        new_crontab = '\n'.join(clean_lines)
                        process = subprocess.Popen(['crontab', '-'], 
                                                 stdin=subprocess.PIPE, text=True)
                        process.communicate(input=new_crontab)
                        self.logger.info("已清理crontab条目")
            except:
                pass
            
            return True
            
        except Exception as e:
            self.logger.error(f"手动清理异常: {e}")
            return False
    
    def generate_test_report(self):
        """生成测试报告"""
        self.logger.info("生成测试报告...")
        
        report = {
            'test_session_id': self.test_session_id,
            'test_time': datetime.now().isoformat(),
            'target_info': {
                'target_ip': self.target_ip,
                'target_user': self.target_user
            },
            'test_results': self.test_results,
            'summary': self._generate_test_summary()
        }
        
        # 保存JSON报告
        report_file = f"reports/persistence_test_report_{self.test_session_id}.json"
        os.makedirs('reports', exist_ok=True)
        
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(report, f, indent=2, ensure_ascii=False)
        
        # 生成Markdown报告
        markdown_report = self._generate_markdown_report(report)
        markdown_file = f"reports/persistence_test_report_{self.test_session_id}.md"
        
        with open(markdown_file, 'w', encoding='utf-8') as f:
            f.write(markdown_report)
        
        self.logger.info(f"测试报告已生成: {report_file}, {markdown_file}")
        
        return report
    
    def _generate_test_summary(self):
        """生成测试摘要"""
        summary = {
            'total_tests': 0,
            'passed_tests': 0,
            'failed_tests': 0,
            'success_rate': 0.0
        }
        
        # 统计测试结果
        for test_category, results in self.test_results.items():
            if isinstance(results, dict):
                for test_name, result in results.items():
                    summary['total_tests'] += 1
                    if isinstance(result, dict) and result.get('deployed', False):
                        summary['passed_tests'] += 1
                    elif result is True:
                        summary['passed_tests'] += 1
                    else:
                        summary['failed_tests'] += 1
        
        if summary['total_tests'] > 0:
            summary['success_rate'] = summary['passed_tests'] / summary['total_tests']
        
        return summary
    
    def _generate_markdown_report(self, report):
        """生成Markdown格式报告"""
        md_content = f"""# Linux权限维持一键化测试报告

## 测试信息
- **测试会话ID**: {report['test_session_id']}
- **测试时间**: {report['test_time']}
- **目标主机**: {report['target_info']['target_ip'] or 'localhost'}
- **目标用户**: {report['target_info']['target_user']}

## 测试摘要
- **总测试数**: {report['summary']['total_tests']}
- **通过测试**: {report['summary']['passed_tests']}
- **失败测试**: {report['summary']['failed_tests']}
- **成功率**: {report['summary']['success_rate']:.2%}

## 详细测试结果

"""
        
        # 添加各项测试结果
        for category, results in report['test_results'].items():
            md_content += f"### {category}\n\n"
            
            if isinstance(results, dict):
                for test_name, result in results.items():
                    status = "✓" if (isinstance(result, dict) and result.get('deployed', False)) or result is True else "✗"
                    md_content += f"- **{test_name}**: {status}\n"
                    
                    if isinstance(result, dict):
                        for key, value in result.items():
                            if key != 'deployed':
                                md_content += f"  - {key}: {value}\n"
            else:
                status = "✓" if results else "✗"
                md_content += f"- **结果**: {status}\n"
            
            md_content += "\n"
        
        md_content += """## 建议

基于测试结果，建议：

1. 对于部署失败的权限维持类型，检查系统兼容性和权限配置
2. 加强隐蔽性措施，提高检测规避能力
3. 完善清理机制，确保测试后环境恢复
4. 定期更新权限维持技术，应对新的检测方法

## 免责声明

本测试仅用于安全研究和授权的渗透测试。请确保在合法授权的环境中使用。
"""
        
        return md_content
    
    def run_full_test(self):
        """运行完整测试"""
        self.logger.info("开始Linux权限维持一键化完整测试...")
        
        # 检查前提条件
        if not self.check_prerequisites():
            self.logger.error("前提条件检查失败，测试终止")
            return False
        
        # 测试本地权限维持部署
        self.test_results['local_deployment'] = self.test_local_persistence_deployment()
        
        # 测试各种权限维持类型
        self.test_results['persistence_types'] = self.test_persistence_types()
        
        # 测试隐蔽性能力
        self.test_results['stealth_capabilities'] = self.test_stealth_capabilities()
        
        # 测试重启后持久化
        self.test_results['persistence_after_reboot'] = self.test_persistence_after_reboot()
        
        # 生成测试报告
        report = self.generate_test_report()
        
        # 清理测试环境
        cleanup_success = self.cleanup_test_environment()
        self.test_results['cleanup'] = cleanup_success
        
        self.logger.info("Linux权限维持一键化测试完成")
        
        return True

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='Linux权限维持一键化测试工具')
    parser.add_argument('--target', '-t', help='目标主机IP地址')
    parser.add_argument('--user', '-u', default='root', help='目标用户名')
    parser.add_argument('--no-cleanup', action='store_true', help='禁用测试后清理')
    parser.add_argument('--test-type', choices=['full', 'local', 'types', 'stealth'], 
                       default='full', help='测试类型')
    
    args = parser.parse_args()
    
    # 创建测试器实例
    tester = LinuxPersistenceTester(target_ip=args.target, target_user=args.user)
    
    if args.no_cleanup:
        tester.test_config['cleanup_enabled'] = False
    
    try:
        if args.test_type == 'full':
            success = tester.run_full_test()
        elif args.test_type == 'local':
            tester.test_results['local_deployment'] = tester.test_local_persistence_deployment()
            success = True
        elif args.test_type == 'types':
            tester.test_results['persistence_types'] = tester.test_persistence_types()
            success = True
        elif args.test_type == 'stealth':
            tester.test_results['stealth_capabilities'] = tester.test_stealth_capabilities()
            success = True
        
        if success:
            print("\n[+] 测试完成，请查看日志和报告文件")
            return 0
        else:
            print("\n[-] 测试失败")
            return 1
            
    except KeyboardInterrupt:
        print("\n[!] 测试被用户中断")
        return 1
    except Exception as e:
        print(f"\n[-] 测试异常: {e}")
        return 1

if __name__ == '__main__':
    sys.exit(main())